package ar.com.photo_admin.domain

import java.util.List;


import org.springframework.dao.DataIntegrityViolationException
import grails.converters.*;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes


class EventController {
	
	final String IMAGES_PATH;
	
	def eventService
	def eventPhotoService;
	def eventAlbumService
	
	static def MIN_FILE_SIZE = 1
	static def MAX_FILE_SIZE = 1000000 //1MB
	static def THUMBNAIL_MODIFICATOR = '' //
	static List ACCEPT_FILE_TYPES = [
		"image/jpeg",
		"image/png",
		"image/gif "
	]


    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	def EventController(){
		IMAGES_PATH = grailsAttributes.getApplicationContext().getResource("images/upload").getFile().toString() + File.separatorChar;
	}
	
    def index() {
        redirect(action: "list", params: params)
		
    }

    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [eventInstanceList: Event.list(params), eventInstanceTotal: Event.count()]
    }

    def create() {
		Event event = new Event(params)
		event.number = (Event.count()+1);
		log.info "NUM"+event.number;
		 
		new File(IMAGES_PATH+event.number).mkdirs();
        render(view: "uploadPhotos", model: [eventInstance: event,eventNumber : event.number,uploaded_files : [],coverPhotoId : 0])
    }

	def save(){
		
		def eventId = params.id
		def coverPhotoId = params.coverId				
		
						
		
		def creating = (eventId == ""); 
		
		def eventInstance = null;
		
		if (creating){
			eventInstance = new Event(params)
			eventInstance.number = (params.eventNumber).toInteger()
		} else{
			eventInstance = Event.get(eventId);			
			eventInstance.properties = params
		}
							
		
		if (!eventInstance.save(flush: true)) {			
			//Fallo la validacion, tengo que recuperar las imagenes que por ahi se confirman.
			//TODO Recupero las imagenes por si mas adelante falla la validacion (no se podria hacer find all despues
			def existingPhotos = eventService.getEventConfirmedAndNotConfirmedPhotosAsJSON(eventId, eventInstance.number);
			render(view: "uploadPhotos", model: [eventInstance: eventInstance, 
												eventNumber : eventInstance.number, 
												coverPhotoId :coverPhotoId, 
												uploaded_files : existingPhotos])
			return
		}
		
		//TODO Se guarda el cover solamente cuando no fallo la validacion. Estaba fallando cuando se asignaba antes. 
		if (coverPhotoId != '0'){
			eventInstance.coverPhoto = EventPhoto.get(coverPhotoId)
			eventInstance.save(flush: true)
		}			
		
		eventService.confirmChangesEvent(eventInstance.id);		
		flash.message = "El evento ha sido guardado";
		
		redirect(action: "show",id:eventInstance.id)
	}
	
    def show() {
        def eventInstance = Event.get(params.id)
        if (!eventInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'event.label', default: 'Event'), params.id])
            redirect(action: "list")
            return
        }

        [eventInstance: eventInstance]
    }

	
    def edit() {					
        def event = Event.get(params.eventId)
        if (!event) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'event.label', default: 'Event'), params.id])
            redirect(action: "list")
            return
        }
		log.info "ID"+event.id
		
		def coverId = (event.coverPhoto != null ? event.coverPhoto.id : 0 );
		
		def existingPhotosAsJSON = eventService.getEventPhotosAsJSON(params.eventId)
        render(view: "uploadPhotos", model: [eventInstance: event,
												eventNumber : event.number,
												coverPhotoId : coverId,
												uploaded_files : existingPhotosAsJSON])				
    }

	
	def deleteAlbum(){
		log.info "Deleting Album"+params.album_id+"from event"+params.event_id;									
		eventAlbumService.deleteAlbum(params.album_id);	
		render(success: true);
		return
	}
	
	
	/*
    def delete() {
        def eventInstance = Event.get(params.id)
        if (!eventInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'event.label', default: 'Event'), params.id])
            redirect(action: "list")
            return
        }

        try {
            eventInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'event.label', default: 'Event'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'event.label', default: 'Event'), params.id])
            redirect(action: "show", id: params.id)
        }
    }*/
	
	
	def cancel(){
		log.info "CANCEL";
		log.info params.eventNumber;
		log.info params.eventId;
		eventService.cancelChangesEvent(params.eventId,params.eventNumber);
		flash.message = message(code: 'event.photoUpload.canceled', default: "Los cambios fueron descartados");
		render(success: true);
		return
	}
	
	
	
	def deleteSelectedPhotosTemporally(){
		log.info "Deleting selected photos: "+params.ids;
		def idsToBeDeleted = (params.ids).split(",");
		idsToBeDeleted.each {
			eventPhotoService.deletePhotoTemporally(it)
		}
		render(success: true);
		return
	}
	
	
	
	

	/**
	 * Carga la pantalla para subir las fotos.
	 */
	/*
	def createUploadPhotos(){
		def eventId = params.event_id;
		if (eventId != null){
			def eventInstance = Event.get(eventId)
			def existingPhotos = eventService.getEventPhotosAsJSON(eventId);
			
			render(view: "uploadPhotos", model: [event_id : eventId,uploaded_files : existingPhotos])
		}
		else{
			log.error "El Id recibido es 0!";
			[]
		}
		
	}
	*/
	/**
	 * Carga la pantalla para subir las fotos con las fotos existenes.
	 */
	/*
	def editUploadPhotos(){
		log.info "Edit upload photos";
		
		if (params.event_id != null){
			def eventInstance = Event.get(params.event_id)
			def existingPhotos = getExistingPhotosAsJSON();
			render(view: "uploadPhotos", model: [event_id : params.event_id,uploaded_files : existingPhotos,eventInstance: params.eventInstance])
		}
		else{
			log.error "El Id recibido es 0!";
			[]
		}
	}
	*/

	

	def uploadAction() {
		
		//Collection que almacena el resultado de todos las fotos recibidas.
		def results = []

		//Mapa que almacena las propiedades de cada foto.
		def result = [:]

		//TODO Por alguna razon llegan requests con content type nulo.
		if (request.getContentType() != null){

			def eventNumber = params.eventNumber
			log.info "El numbero de evento asociado asociado es"+params.eventNumber ;
			//Event eventInstance = eventService.findEventById(eventId)

			DefaultMultipartHttpServletRequest filesRequest = (DefaultMultipartHttpServletRequest) request

			Iterator itr = filesRequest.getFileNames();

			def photoDir;

			
			while(itr.hasNext()) {
					
				def file = filesRequest.getFile(itr.next());

				def fileName = file.getOriginalFilename();
				result['name'] = fileName
				result['size'] = file.getSize()
				result['type'] = file.getContentType()

				def validationResult = validateFile(result);

				if(validationResult){
															
					EventPhoto photo = eventPhotoService.createPhotoTemporally(eventNumber,file.getBytes(),file.getOriginalFilename());
					log.info "El id de la foto es" + photo.id ;
					result['photoId'] = photo.id;
					result['url'] = photo.url;
					result['thumbnailUrl'] = photo.thumbnailUrl;

				}
				else{
					result['delete_type'] = 'DELETE'
				}

				results << result

			}

		}
		
		//Devuelvo un mapa en formato JSON con los resultados.
		render results as JSON
	}

	def validateFile(def result){
		if (result['size'] < MIN_FILE_SIZE)
		result['error'] = 'minFileSize'
		else if (result['size'] > MAX_FILE_SIZE)
		result['error'] = 'maxFileSize'
		else if (! ACCEPT_FILE_TYPES.contains(result['type']))
		result['error'] = 'acceptFileTypes'
		else
			return true
		return false
	}
}
